package com.aspire.aimini.controller;

import com.aspire.aimini.model.entity.Copywriting;
import com.aspire.aimini.service.CopywritingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 文案管理控制器
 *
 * @author wangguiyou
 * @date 2024-12-19
 */
@Slf4j
@RestController
@RequestMapping("/api/copywritings")
@RequiredArgsConstructor
@Tag(name = "文案管理", description = "文案相关的API接口")
public class CopywritingController {

    private final CopywritingService copywritingService;

    /**
     * 生成文案
     *
     * @param request 生成请求
     * @return 生成的文案
     */
    @PostMapping("/generate")
    @Operation(summary = "生成文案", description = "使用AI生成文案")
    public ResponseEntity<Copywriting> generateCopywriting(
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("生成文案: userId={}", userId);

        String prompt = (String) request.get("prompt");
        String contentType = (String) request.get("contentType");
        String style = (String) request.get("style");
        String aiModel = (String) request.get("aiModel");

        Copywriting copywriting = copywritingService.generateCopywriting(userId, prompt, contentType, style, aiModel);
        return ResponseEntity.ok(copywriting);
    }

    /**
     * 批量生成文案
     *
     * @param request 批量生成请求
     * @return 生成的文案列表
     */
    @PostMapping("/generate/batch")
    @Operation(summary = "批量生成文案", description = "批量生成多个文案")
    public ResponseEntity<List<Copywriting>> batchGenerateCopywriting(
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("批量生成文案: userId={}", userId);

        @SuppressWarnings("unchecked")
        List<String> prompts = (List<String>) request.get("prompts");
        String contentType = (String) request.get("contentType");
        String style = (String) request.get("style");
        String aiModel = (String) request.get("aiModel");

        List<Copywriting> copywritings = copywritingService.batchGenerateCopywriting(userId, prompts, contentType,
                style, aiModel);
        return ResponseEntity.ok(copywritings);
    }

    /**
     * 分页查询文案
     *
     * @param page        页码
     * @param size        每页大小
     * @param sort        排序字段
     * @param direction   排序方向
     * @param contentType 内容类型
     * @param style       风格
     * @param userId      用户ID
     * @return 文案分页列表
     */
    @GetMapping
    @Operation(summary = "分页查询文案", description = "根据条件分页查询文案列表")
    public ResponseEntity<Page<Copywriting>> getCopywritings(
            @Parameter(description = "页码") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "20") int size,
            @Parameter(description = "排序字段") @RequestParam(defaultValue = "createdAt") String sort,
            @Parameter(description = "排序方向") @RequestParam(defaultValue = "desc") String direction,
            @Parameter(description = "内容类型") @RequestParam(required = false) String contentType,
            @Parameter(description = "风格") @RequestParam(required = false) String style,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {

        Sort.Direction sortDirection = "asc".equalsIgnoreCase(direction) ? Sort.Direction.ASC : Sort.Direction.DESC;
        Pageable pageable = PageRequest.of(page, size, Sort.by(sortDirection, sort));

        Page<Copywriting> copywritings = copywritingService.getCopywritings(userId, pageable, contentType, style);
        return ResponseEntity.ok(copywritings);
    }

    /**
     * 根据ID获取文案
     *
     * @param id 文案ID
     * @return 文案信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取文案详情", description = "根据ID获取文案详细信息")
    public ResponseEntity<Copywriting> getCopywritingById(
            @Parameter(description = "文案ID") @PathVariable Long id) {
        log.info("获取文案详情: id={}", id);

        Copywriting copywriting = copywritingService.getCopywritingById(id);
        return ResponseEntity.ok(copywriting);
    }

    /**
     * 更新文案
     *
     * @param id          文案ID
     * @param copywriting 文案信息
     * @return 更新后的文案
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新文案", description = "更新文案信息")
    public ResponseEntity<Copywriting> updateCopywriting(
            @Parameter(description = "文案ID") @PathVariable Long id,
            @Valid @RequestBody Copywriting copywriting,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("更新文案: id={}, userId={}", id, userId);

        Copywriting updatedCopywriting = copywritingService.updateCopywriting(id, copywriting);
        return ResponseEntity.ok(updatedCopywriting);
    }

    /**
     * 删除文案
     *
     * @param id 文案ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除文案", description = "删除指定的文案")
    public ResponseEntity<Void> deleteCopywriting(
            @Parameter(description = "文案ID") @PathVariable Long id,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("删除文案: id={}, userId={}", id, userId);

        copywritingService.deleteCopywriting(id);
        return ResponseEntity.ok().build();
    }

    /**
     * 批量删除文案
     *
     * @param ids 文案ID列表
     * @return 删除结果
     */
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除文案", description = "批量删除多个文案")
    public ResponseEntity<Void> batchDeleteCopywritings(
            @Parameter(description = "文案ID列表") @RequestBody List<Long> ids,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("批量删除文案: ids={}, userId={}", ids, userId);

        copywritingService.batchDeleteCopywritings(ids);
        return ResponseEntity.ok().build();
    }

    /**
     * 增加文案使用次数
     *
     * @param id 文案ID
     * @return 更新后的文案
     */
    @PostMapping("/{id}/increment-usage")
    @Operation(summary = "增加文案使用次数", description = "增加文案的使用次数")
    public ResponseEntity<Copywriting> incrementUsageCount(
            @Parameter(description = "文案ID") @PathVariable Long id) {
        log.info("增加文案使用次数: id={}", id);

        Copywriting copywriting = copywritingService.incrementUsageCount(id);
        return ResponseEntity.ok(copywriting);
    }

    /**
     * 获取收藏的文案
     *
     * @param userId   用户ID
     * @param pageable 分页参数
     * @return 收藏的文案列表
     */
    @GetMapping("/favorites")
    @Operation(summary = "获取收藏的文案", description = "获取用户收藏的文案列表")
    public ResponseEntity<Page<Copywriting>> getFavoriteCopywritings(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "20") int size) {
        log.info("获取收藏的文案: userId={}", userId);

        Pageable pageable = PageRequest.of(page, size);
        Page<Copywriting> copywritings = copywritingService.getFavoriteCopywritings(userId, pageable);
        return ResponseEntity.ok(copywritings);
    }

    /**
     * 获取最近的文案
     *
     * @param userId 用户ID
     * @param limit  数量限制
     * @return 最近的文案列表
     */
    @GetMapping("/recent")
    @Operation(summary = "获取最近的文案", description = "获取用户最近生成的文案")
    public ResponseEntity<List<Copywriting>> getRecentCopywritings(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId,
            @Parameter(description = "数量限制") @RequestParam(defaultValue = "10") int limit) {
        log.info("获取最近的文案: userId={}, limit={}", userId, limit);

        List<Copywriting> copywritings = copywritingService.getRecentCopywritings(userId, limit);
        return ResponseEntity.ok(copywritings);
    }

    /**
     * 获取热门文案
     *
     * @param limit 数量限制
     * @return 热门文案列表
     */
    @GetMapping("/popular")
    @Operation(summary = "获取热门文案", description = "获取使用次数最多的文案")
    public ResponseEntity<List<Copywriting>> getPopularCopywritings(
            @Parameter(description = "数量限制") @RequestParam(defaultValue = "10") int limit) {
        log.info("获取热门文案: limit={}", limit);

        List<Copywriting> copywritings = copywritingService.getPopularCopywritings(limit);
        return ResponseEntity.ok(copywritings);
    }

    /**
     * 搜索文案
     *
     * @param keyword 搜索关键词
     * @param page    页码
     * @param size    每页大小
     * @return 搜索结果
     */
    @GetMapping("/search")
    @Operation(summary = "搜索文案", description = "根据关键词搜索文案")
    public ResponseEntity<Page<Copywriting>> searchCopywritings(
            @Parameter(description = "搜索关键词") @RequestParam String keyword,
            @Parameter(description = "页码") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "20") int size) {
        log.info("搜索文案: keyword={}", keyword);

        Pageable pageable = PageRequest.of(page, size);
        Page<Copywriting> copywritings = copywritingService.searchCopywritings(keyword, pageable);
        return ResponseEntity.ok(copywritings);
    }

    /**
     * 按内容类型统计文案数量
     *
     * @param userId 用户ID
     * @return 统计结果
     */
    @GetMapping("/statistics/by-content-type")
    @Operation(summary = "按内容类型统计文案数量", description = "统计每个内容类型下的文案数量")
    public ResponseEntity<Map<String, Long>> getCopywritingCountByContentType(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("按内容类型统计文案数量: userId={}", userId);

        Map<String, Long> statistics = copywritingService.getCopywritingCountByContentType(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 按风格统计文案数量
     *
     * @param userId 用户ID
     * @return 统计结果
     */
    @GetMapping("/statistics/by-style")
    @Operation(summary = "按风格统计文案数量", description = "统计每个风格下的文案数量")
    public ResponseEntity<Map<String, Long>> getCopywritingCountByStyle(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("按风格统计文案数量: userId={}", userId);

        Map<String, Long> statistics = copywritingService.getCopywritingCountByStyle(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 按AI模型统计文案数量
     *
     * @param userId 用户ID
     * @return 统计结果
     */
    @GetMapping("/statistics/by-ai-model")
    @Operation(summary = "按AI模型统计文案数量", description = "统计每个AI模型生成的文案数量")
    public ResponseEntity<Map<String, Long>> getCopywritingCountByAiModel(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("按AI模型统计文案数量: userId={}", userId);

        Map<String, Long> statistics = copywritingService.getCopywritingCountByAiModel(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 获取用户文案统计信息
     *
     * @param userId 用户ID
     * @return 统计信息
     */
    @GetMapping("/statistics/user")
    @Operation(summary = "获取用户文案统计信息", description = "获取用户的文案统计信息")
    public ResponseEntity<Map<String, Object>> getUserCopywritingStatistics(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取用户文案统计信息: userId={}", userId);

        Map<String, Object> statistics = copywritingService.getUserCopywritingStatistics(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 统计每日生成数量
     *
     * @param userId 用户ID
     * @param days   天数
     * @return 每日生成统计
     */
    @GetMapping("/statistics/daily-generation")
    @Operation(summary = "统计每日生成数量", description = "统计用户每日文案生成数量")
    public ResponseEntity<Map<String, Long>> getDailyGenerationCount(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId,
            @Parameter(description = "天数") @RequestParam(defaultValue = "7") int days) {
        log.info("统计每日生成数量: userId={}, days={}", userId, days);

        Map<String, Long> statistics = copywritingService.getDailyGenerationCount(userId, days);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 清理过期临时文案
     *
     * @param days 过期天数
     * @return 清理结果
     */
    @PostMapping("/cleanup-expired")
    @Operation(summary = "清理过期临时文案", description = "清理过期的临时文案")
    public ResponseEntity<Map<String, Object>> cleanupExpiredTempCopywritings(
            @Parameter(description = "过期天数") @RequestParam(defaultValue = "7") int days) {
        log.info("清理过期临时文案: days={}", days);

        int cleanedCount = copywritingService.cleanupExpiredTempCopywritings(days);

        Map<String, Object> result = Map.of(
                "cleanedCount", cleanedCount,
                "message", "清理完成");

        return ResponseEntity.ok(result);
    }

    /**
     * 复制文案
     *
     * @param id 文案ID
     * @return 复制的文案
     */
    @PostMapping("/{id}/copy")
    @Operation(summary = "复制文案", description = "复制指定的文案")
    public ResponseEntity<Copywriting> copyCopywriting(
            @Parameter(description = "文案ID") @PathVariable Long id,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("复制文案: id={}, userId={}", id, userId);

        Copywriting copiedCopywriting = copywritingService.copyCopywriting(id, userId);
        return ResponseEntity.ok(copiedCopywriting);
    }

    /**
     * 重新生成文案
     *
     * @param id 文案ID
     * @return 重新生成的文案
     */
    @PostMapping("/{id}/regenerate")
    @Operation(summary = "重新生成文案", description = "基于原文案重新生成")
    public ResponseEntity<Copywriting> regenerateCopywriting(
            @Parameter(description = "文案ID") @PathVariable Long id,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("重新生成文案: id={}, userId={}", id, userId);

        Copywriting regeneratedCopywriting = copywritingService.regenerateCopywriting(id, userId);
        return ResponseEntity.ok(regeneratedCopywriting);
    }

    /**
     * 导出文案
     *
     * @param request 导出请求
     * @return 导出任务ID
     */
    @PostMapping("/export")
    @Operation(summary = "导出文案", description = "导出文案数据")
    public ResponseEntity<Map<String, Object>> exportCopywritings(
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("导出文案: userId={}", userId);

        String format = (String) request.get("format");
        @SuppressWarnings("unchecked")
        List<Long> ids = (List<Long>) request.get("ids");

        String exportTaskId = copywritingService.exportCopywritings(userId, ids, format);

        Map<String, Object> result = Map.of(
                "exportTaskId", exportTaskId,
                "message", "导出任务已创建");

        return ResponseEntity.ok(result);
    }

    /**
     * 获取可用的内容类型
     *
     * @return 内容类型列表
     */
    @GetMapping("/content-types")
    @Operation(summary = "获取可用的内容类型", description = "获取所有可用的文案内容类型")
    public ResponseEntity<List<String>> getAvailableContentTypes() {
        log.info("获取可用的内容类型");

        List<String> contentTypes = copywritingService.getAvailableContentTypes();
        return ResponseEntity.ok(contentTypes);
    }

    /**
     * 获取可用的风格
     *
     * @return 风格列表
     */
    @GetMapping("/styles")
    @Operation(summary = "获取可用的风格", description = "获取所有可用的文案风格")
    public ResponseEntity<List<String>> getAvailableStyles() {
        log.info("获取可用的风格");

        List<String> styles = copywritingService.getAvailableStyles();
        return ResponseEntity.ok(styles);
    }
}